package com.kyc.kycxkplaygame.activity;

import android.content.*;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.kyc.kycxkplaygame.R;
import com.kyc.kycxkplaygame.dbutils.GetPropLevelUtils;
import com.kyc.kycxkplaygame.dbutils.IntImp.AlasbusyIApi;
import com.kyc.kycxkplaygame.dbutils.inter.HttpQuestResultListener;
import com.kyc.kycxkplaygame.entity.PropsCode;
import com.kyc.kycxkplaygame.entity.UsersProps;
import com.kyc.kycxkplaygame.greendao.LevelPassBean;
import com.kyc.kycxkplaygame.greendao.PropInfoBean;
import com.kyc.kycxkplaygame.greendao.manager.LevelInfoManager;
import com.kyc.kycxkplaygame.greendao.manager.PropInfoManager;
import com.kyc.kycxkplaygame.service.MusicBgService;
import com.kyc.kycxkplaygame.service.TimeTiliService;
import com.kyc.kycxkplaygame.util.ConstactUtil;
import com.kyc.kycxkplaygame.util.SharedPreferencesUtils;
import com.kyc.kycxkplaygame.util.TimeUtil;
import com.zhy.android.percent.support.PercentLinearLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import static com.kyc.kycxkplaygame.util.SharedPreferencesUtils.getParam;

public class LevelActivity extends AppCompatActivity implements View.OnClickListener, HttpQuestResultListener {

    private PercentLinearLayout lin_layout;
    public String[] level_num = {
            "01",
            "02",
            "03",
            "04",
            "05",
            "06",
            "07",
            "08",
            "09",
            "10",
            "11",
            "12"
    };

    public int levelPageCount = 12;

    public int startLevel = 1;

    private List<String> levelList = new ArrayList<>();
    private int isID = -1;
    private int level;
    private ImageView img_up;
    private ImageView img_down;
    private TextView tili_txt;
    private TextView huob_txt;
    private String tili_num;
    private String huob_num;

    public static LevelActivity instanse;

    private Handler handler = new Handler();

    private Intent tiliIntent;
    private TiliReceiver receiver;
    private ImageView setting_img;
    private ImageView my_shoppingcar;
    private Intent musicBgIntent;
    private MusicBgService musicBgService;
    private MediaPlayer mPlayer;
    private boolean yx_open;
    private AlasbusyIApi alasbusyIApi;
    private String phone;
    private TextView pay_money_txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_level);
        instanse = this;
        lin_layout = (PercentLinearLayout) findViewById(R.id.lin_layout);
        img_up = (ImageView) findViewById(R.id.img_up);
        img_down = (ImageView) findViewById(R.id.img_down);

        tili_txt = (TextView) findViewById(R.id.tili_txt);
        huob_txt = (TextView) findViewById(R.id.huob_txt);

        setting_img = findViewById(R.id.setting_img);
        my_shoppingcar = findViewById(R.id.my_shoppingcar);

        pay_money_txt = findViewById(R.id.pay_money_txt);


        tili_num = GetPropLevelUtils.getInstance().getPropNum("体力");

        phone = (String) SharedPreferencesUtils.getParam(LevelActivity.this, "phone", "");

        yx_open = (boolean) SharedPreferencesUtils.getParam(this, "yx_open", true);

        level = GetPropLevelUtils.getInstance().getLevel();
        // tili_num = (String) SharedPreferencesUtils.getParam(LevelActivity.this, "tili_num", "");
        //huob_num = (String) SharedPreferencesUtils.getParam(LevelActivity.this, "huob_num", "");
        //level = (int) SharedPreferencesUtils.getParam(LevelActivity.this, "level", 0);
        tili_txt.setText(tili_num + "/5");
        //handler.postDelayed(TimeRunable, 1000);

        setGrape_curr();

        img_up.setOnClickListener(this);
        img_down.setOnClickListener(this);
        tili_txt.setOnClickListener(this);
        huob_txt.setOnClickListener(this);
        setting_img.setOnClickListener(this);
        my_shoppingcar.setOnClickListener(this);

        alasbusyIApi = AlasbusyIApi.getInstance(this);
        alasbusyIApi.setHttpQuestResultListener(this);

        pay_money_txt.setOnClickListener(this);


        onFirstLevel(startLevel, startLevel + levelPageCount);

        startTiliServices();

        //startMusicBgServices();

        musicBgService = new MusicBgService();

        receiver = new TiliReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConstactUtil.TimeAction);
        filter.addAction(ConstactUtil.UpdateGrapeAction);
        filter.addAction(ConstactUtil.UseTiliProp);
        LevelActivity.this.registerReceiver(receiver, filter);
    }

    private void setGrape_curr() {
        huob_num = GetPropLevelUtils.getInstance().getPropNum("葡萄");
        //Log.i("KYCC","putao ==== " + huob_num);
        if (!TextUtils.isEmpty(huob_num)) {
            if (huob_num.length() >= 5) {
                if ((Integer.parseInt(huob_num) % 10000) == 0) {
                    int num_hb = Integer.parseInt(huob_num) / 10000;
                    huob_txt.setText(num_hb + "万");
                } else {
                    int num_hb = Integer.parseInt(huob_num) / 10000;
                    int num_hbb = Integer.parseInt(huob_num) % 10000;
                    String sub_num = String.valueOf(num_hbb).substring(0, 2).replace("0", "");
                    huob_txt.setText(num_hb + "." + sub_num + "万");
                }
            } else {
                huob_txt.setText(huob_num);
            }
        } else {
            huob_txt.setText("0");
        }
    }

    @Override
    public void onError(Object e) {

    }

    @Override
    public void onSuccess(Object object) {
        if (object instanceof PropsCode) {
            PropsCode propsCode = (PropsCode) object;
            if (propsCode.getCode() == 200) {
                Log.i("KYCC", propsCode.getMessage());
            }
        }
        if (object instanceof UsersProps) {
            UsersProps usersProps = (UsersProps) object;
            List<UsersProps.UserPropsBean> userProps = usersProps.getUserProps();
            if (userProps.size() > 0) {
                final List<PropInfoBean> list = new ArrayList<>();
                for (UsersProps.UserPropsBean bean : userProps) {
                    PropInfoBean propInfoBean = new PropInfoBean();
                    propInfoBean.setUserName(GetPropLevelUtils.getInstance().getUserName());
                    propInfoBean.setPropName(bean.getPropName());
                    propInfoBean.setPropNum(bean.getPropNum());
                    propInfoBean.setId(bean.getUpID());
                    list.add(propInfoBean);
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        PropInfoManager.getInstance().insertPropInfo(list);
                    }
                }).start();
            }
        }
    }

    @Override
    public void onQuestErroCode(Object object) {
        if (object instanceof PropsCode) {
            PropsCode propsCode = (PropsCode) object;
            //Toasty.error(LevelActivity.this,propsCode.getMessage()).show();
        }
    }

    public class TiliReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(ConstactUtil.TimeAction)) {
                Bundle bundle = intent.getExtras();
                int count = bundle.getInt("tili");
                SharedPreferencesUtils.setParam(LevelActivity.this, "oldtime", TimeUtil.getNowYMDHMSTime());
                //Log.i("KYCC", "count Receiver  === " + count);
                setTili(count);
            } else if (intent.getAction().equals(ConstactUtil.UpdateGrapeAction)) {
                //String propNumtime = GetPropLevelUtils.getInstance().getPropNum("葡萄");
                //Log.i("KYCC", " 葡萄  === ");
                setGrape_curr();
            }else if(intent.getAction().equals(ConstactUtil.UseTiliProp)){
                Bundle bundle = intent.getExtras();
                int num = bundle.getInt("num");
                setTili(num);
            }
        }
    }

    private void startTiliServices() {
        tiliIntent = new Intent(LevelActivity.this, TimeTiliService.class);
        startService(tiliIntent);
    }

  /*  private void startMusicBgServices() {
        musicBgIntent = new Intent(LevelActivity.this, MusicBgService.class);
        startService(musicBgIntent);
    }*/

    @Override
    protected void onStart() {
        super.onStart();
        setTili(0);
        setGrape_curr();
        alasbusyIApi.findUserProp(phone);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //musicBgService.play();
        yx_open = (boolean) getParam(this, "yx_open", true);
        if (yx_open) {
            play();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // musicBgService.pause();
        yx_open = (boolean) getParam(this, "yx_open", true);
        if (yx_open) {
            pause();
        }
    }

    private void createLayout(int index, int size) {
        LinearLayout.LayoutParams Linparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Linparams.gravity = Gravity.CENTER;
        Linparams.weight = 1;
        LinearLayout layout_01 = new LinearLayout(this);
        LinearLayout layout_02 = new LinearLayout(this);
        LinearLayout layout_03 = new LinearLayout(this);
        layout_01.setOrientation(LinearLayout.HORIZONTAL);
        layout_01.setLayoutParams(Linparams);
        layout_02.setOrientation(LinearLayout.HORIZONTAL);
        layout_02.setLayoutParams(Linparams);
        layout_03.setOrientation(LinearLayout.HORIZONTAL);
        layout_03.setLayoutParams(Linparams);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(5, 5, 5, 5);
        params.weight = 1;
        params.gravity = Gravity.CENTER;
        int i = 0;
        for (String str : levelList) {
            int anInt = Integer.parseInt(str);
            final Button btn = new Button(this);
            btn.setText(str/*levelList.get(i)*/);
            btn.setTextSize(18);
            btn.setId(anInt);
            if (level == 0) {
                if (anInt == 1) {
                    btn.setBackgroundResource(R.drawable.level_yuan);
                    btn.setTextColor(getResources().getColor(R.color.white));
                    btn.setLayoutParams(params);
                    btn.setEnabled(true);
                } else {
                    btn.setBackgroundResource(R.drawable.level_nolock);
                    btn.setTextColor(getResources().getColor(R.color.no_clearance));
                    btn.setLayoutParams(params);
                    btn.setEnabled(false);
                }
            } else {
                if (anInt < level) {
                    /*HashMap<String, PassStatusBean> pass_status = SharedPreferencesUtils.getHashMapData(LevelActivity.this, "pass_status", PassStatusBean.class);
                    for (Map.Entry<String, PassStatusBean> set : pass_status.entrySet()) {
                        if (!TextUtils.isEmpty(set.getKey())) {
                            int setKey = Integer.parseInt(set.getKey());
                            PassStatusBean setValue = set.getValue();
                            if (Integer.parseInt(setValue.getLevel()) == anInt) {
                                if (setValue.getFraction().equals("1")) {
                                    btn.setBackgroundResource(R.drawable.one_pass);
                                } else if (setValue.getFraction().equals("2")) {
                                    btn.setBackgroundResource(R.drawable.two_pass);
                                } else if (setValue.getFraction().equals("3")) {
                                    btn.setBackgroundResource(R.drawable.three_pass);
                                }
                            }
                        } else {
                            btn.setBackgroundResource(R.drawable.level_yuan);
                        }
                    }*/

                    List<LevelPassBean> levelPassBeen = LevelInfoManager.getInstance().getUserInfo();
                    if (levelPassBeen.size() > 0) {
                        for (LevelPassBean bean : levelPassBeen) {
                            //Log.i("KYCC","level === + " + bean.getLevel()+" , starCount == " + bean.getStarCount());
                            if (Integer.parseInt(bean.getLevel()) == anInt) {
                                if (bean.getStarCount() == 1) {
                                    btn.setBackgroundResource(R.drawable.one_pass);
                                } else if (bean.getStarCount() == 2) {
                                    btn.setBackgroundResource(R.drawable.two_pass);
                                } else if (bean.getStarCount() == 3) {
                                    btn.setBackgroundResource(R.drawable.three_pass);
                                }
                            }
                        }
                    } else {
                        btn.setBackgroundResource(R.drawable.level_yuan);
                    }
                    btn.setTextColor(getResources().getColor(R.color.c_006C90));
                    btn.setLayoutParams(params);
                } else if (anInt == level) {
                    btn.setBackgroundResource(R.drawable.level_yuan);
                    btn.setTextColor(getResources().getColor(R.color.white));
                    btn.setLayoutParams(params);
                    btn.setEnabled(true);
                } else {
                    btn.setBackgroundResource(R.drawable.level_nolock);
                    btn.setTextColor(getResources().getColor(R.color.no_clearance));
                    btn.setLayoutParams(params);
                    btn.setEnabled(false);
                }
            }
            i++;
            if (i < 5) {
                layout_01.addView(btn);
            } else if (i >= 5 && i < 9) {
                layout_02.addView(btn);
            } else {
                layout_03.addView(btn);
            }

            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int id = view.getId();
                    Button button = (Button) findViewById(id);
                    Intent intent = new Intent(LevelActivity.this, StartPlayActivity.class);
                    intent.putExtra("level_num", button.getText().toString());
                    intent.putExtra("tili_num", tili_num);
                    startActivity(intent);
                }
            });
        }
        lin_layout.addView(layout_01);
        lin_layout.addView(layout_02);
        lin_layout.addView(layout_03);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_up:
                //上一页关卡
                onFirstLevel(startLevel - levelPageCount * 2, startLevel - levelPageCount);
                //13,24
                break;
            case R.id.img_down:
                //下一页关卡
                onFirstLevel(startLevel, startLevel + levelPageCount);
                //25 37
                break;
            case R.id.tili_txt:
                int xiyou = Integer.parseInt(GetPropLevelUtils.getInstance().getPropNum("西柚"));//(int) getParam(LevelActivity.this, "xiyou", 0);
                int caomei = Integer.parseInt(GetPropLevelUtils.getInstance().getPropNum("青苹果"));//(int) getParam(LevelActivity.this, "apple", 0);
                int putao = Integer.parseInt(GetPropLevelUtils.getInstance().getPropNum("西瓜"));//(int) getParam(LevelActivity.this, "xigua", 0);
                Intent intent = new Intent(LevelActivity.this, UseAndBuyTiliActivity.class);
                intent.putExtra("xiyou", xiyou);
                intent.putExtra("caomei", caomei);
                intent.putExtra("putao", putao);
                intent.putExtra("tili_num", tili_num);
                startActivity(intent);
                /*if(xiyou <= 0) {
                    Intent intent = new Intent(LevelActivity.this, PropsBuyActivity.class);
                    intent.putExtra("daoju", "xiyou");
                    startActivity(intent);
                }else {
                    //使用道具
                }*/
                break;
            case R.id.huob_txt:
                break;
            case R.id.setting_img:
                startActivity(new Intent(LevelActivity.this, MyInfoDialogActivity.class));
                break;
            case R.id.my_shoppingcar:
                Intent shoping = new Intent(this, ShoppingActivity.class);
                shoping.putExtra("state","normal");
                startActivity(shoping);
                break;
            case R.id.pay_money_txt:
                Intent shoppCaomeiing = new Intent(this, ShoppingActivity.class);
                shoppCaomeiing.putExtra("state","caomei");
                startActivity(shoppCaomeiing);
                break;
        }
    }

    private void onFirstLevel(int startIndex, int endIndex) {
        levelList.clear();
        for (int i = startIndex; i < endIndex; i++) {
            String a = i + "";
            if (a.length() >= 2) {
                levelList.add(a);
            } else {
                levelList.add("0" + a);
            }
        }
        lin_layout.removeAllViews();
        createLayout(Integer.parseInt(levelList.get(0)), Integer.parseInt(levelList.get(levelList.size() - 1)));
        if ((level > 12 && startIndex > 12) || startIndex > 12) {
            img_up.setVisibility(View.VISIBLE);
            img_up.setEnabled(true);
        } else {
            img_up.setVisibility(View.INVISIBLE);
            img_up.setEnabled(false);
        }
        startLevel = endIndex;
    }

    /*Runnable TimeRunable = new Runnable() {
        @Override
        public void run() {
            if (TextUtils.isEmpty(tili_num)) {
                //开始计时 5分钟之后+1
                handler.postDelayed(TimeRunable, 60000);
                tili_txt.setText("0/5");
            } else {
                if (Integer.parseInt(tili_num) < 5) {
                    //开始计时 5分钟之后+1
                    handler.postDelayed(TimeRunable, 60000);
                } else {
                    //停止计时
                    handler.removeCallbacks(TimeRunable);
                }
                tili_txt.setText(tili_num + "/5");
            }
        }
    };*/

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
                .setCancelable(true)
                .setTitle("退出游戏")
                .setMessage("确定退出当前游戏吗?")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (tiliIntent != null) {
                            stopService(tiliIntent);
                        }
                        LevelActivity.this.finish();

                    }
                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        }).show();
    }

    public void setTili(int tiobj) {
        //tili_num = (String) SharedPreferencesUtils.getParam(LevelActivity.this, "tili_num", "");
        /*List<PropInfoBean> tiliList = PropInfoManager.getInstance().getInfoPropname("体力");
        PropInfoBean propInfoBean = tiliList.get(0);*/
        String propNum = GetPropLevelUtils.getInstance().getPropNum("体力");
        Log.i("KYCC -- ", "settili ===  " + propNum);
        if (TextUtils.isEmpty(propNum)) {
            //SharedPreferencesUtils.setParam(LevelActivity.this, "tili_num", String.valueOf(tiobj));
           /* PropInfoBean propInfo = new PropInfoBean();
            propInfo.setPropName("体力");
            propInfo.setPropNum(tiobj);
            PropInfoManager.getInstance().updatePropInfo(propInfo);*/
            GetPropLevelUtils.getInstance().updatePropNum("体力", tiobj);
            alasbusyIApi.insertProps(phone, "体力", tiobj);
            tili_num = String.valueOf(tiobj);
            tili_txt.setText(tiobj + "/5");
        } else {
            int ti = Integer.parseInt(propNum); //Integer.parseInt(tili_num);
            if ((ti + tiobj) > 5) {
                //SharedPreferencesUtils.setParam(LevelActivity.this, "tili_num", "5");
               /* PropInfoBean propInfo = new PropInfoBean();
                propInfo.setPropName("体力");
                propInfo.setPropNum(5);
                PropInfoManager.getInstance().updatePropInfo(propInfo);*/
                GetPropLevelUtils.getInstance().updatePropNum("体力", 5);
                alasbusyIApi.insertProps(phone, "体力", 5);
                tili_num = "5";
                tili_txt.setText("5/5");
            } else {
                int count = ti + tiobj;
                // SharedPreferencesUtils.setParam(LevelActivity.this, "tili_num", String.valueOf(count));
               /* PropInfoBean propInfo = new PropInfoBean();
                propInfo.setPropName("体力");
                propInfo.setPropNum(count);
                PropInfoManager.getInstance().updatePropInfo(propInfo);*/
                GetPropLevelUtils.getInstance().updatePropNum("体力", count);
                alasbusyIApi.insertProps(phone, "体力", count);
                tili_num = String.valueOf(count);
                tili_txt.setText(count + "/5");
            }
        }
    }


    @Override
    protected void onDestroy() {
        //tiliIntent = new Intent(LevelActivity.this, TimeTiliService.class);
        LevelActivity.this.unregisterReceiver(receiver);
        stopService(tiliIntent);
        //stopService(musicBgIntent);

        super.onDestroy();
    }

    public int[] mBgMusic = {R.raw.m_bg1, R.raw.m_bg2};

    public void play() {
        mPlayer = new MediaPlayer();
        Random random = new Random();
        int nextInt = random.nextInt(1);
        Log.i("KYCC", "nextInt   ==== " + nextInt);
        AssetFileDescriptor file = getResources().openRawResourceFd(mBgMusic[nextInt]);
        try {
            mPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(),
                    file.getLength());
            mPlayer.prepare();
            file.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mPlayer.start();
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                play();
            }
        });
    }

    public void pause() {
        mPlayer.pause();
    }

    public void stop() {
        if (mPlayer != null) {
            mPlayer.stop();
            mPlayer.release();
        }
    }

}
